/*
 * Copyright (c) 2019, XXX All Rights Reserved.
 */
package net.sf.log4jdbc.sql.rdbmsspecifics;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;

/**
 * RDBMS specifics for the Postgresql DB.
 *
 * @author zhanxb
 * @since 2021/8/2
 **/
public class PostgresqlRdbmsSpecifics extends RdbmsSpecifics{
    public PostgresqlRdbmsSpecifics() {
        super();
    }

    @Override
    public String formatParameterObject(Object object)
    {
        if (object instanceof java.sql.Time)
        {
            return "'" + new SimpleDateFormat("HH:mm:ss").format(object) + "'";
        }
        else if (object instanceof java.sql.Date)
        {
            return "'" + new SimpleDateFormat("yyyy-MM-dd").format(object) + "'";
        }
        else if (object instanceof java.util.Date)  // (includes java.sql.Timestamp)
        {
            return "'" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(object) + "'";
        }
        else if(LOCAL_DATE_TIME.equals(object.getClass().getName())){
            try {
                Class<?> localeDateTime = Class.forName(LOCAL_DATE_TIME);
                Class<?> formatter = Class.forName("java.time.format.DateTimeFormatter");
                Method ofPattern = formatter.getDeclaredMethod("ofPattern",String.class);
                Object ofPatternResult = ofPattern.invoke(formatter,"yyyy-MM-dd HH:mm:ss");
                Method format = localeDateTime.getDeclaredMethod("format",formatter);
                Object result = format.invoke(object,ofPatternResult);
                return "'"+result+"'";
            }catch (Exception e){
                return object.toString();
            }
        }
        else if(LOCAL_DATE.equals(object.getClass().getName())){
            try {
                Class<?> localeDateTime = Class.forName(LOCAL_DATE);
                Class<?> formatter = Class.forName("java.time.format.DateTimeFormatter");
                Method ofPattern = formatter.getDeclaredMethod("ofPattern",String.class);
                Object ofPatternResult = ofPattern.invoke(formatter,"yyyy-MM-dd");
                Method format = localeDateTime.getDeclaredMethod("format",formatter);
                Object result = format.invoke(object,ofPatternResult);
                return "'"+result+"'";
            }catch (Exception e){
                return object.toString();
            }
        }
        else
        {
            return super.formatParameterObject(object);
        }
    }
}
